package cn.zifangsky.service.impl;

import cn.zifangsky.service.CacheService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

/**
 *
 * @author yaokai
 * @date 2023/05/31
 * @since 1.0.0
 */
@Service("concurrentHashMapCacheServiceImpl")
public class ConcurrentHashMapCacheServiceImpl implements CacheService {

    @Autowired
    private Map<String, Object> map = new ConcurrentHashMap();

    @Override
    public void set(String key, Object value) {
        map.put(key, value);
    }

    @Override
    public void setWithExpire(String key, Object value, long time, TimeUnit timeUnit) {
        map.put(key, value);
        new Thread(()->{
            try {
                timeUnit.sleep(time);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            map.remove(key);
        }).start();
    }

    @Override
    public <K> K get(String key) {


        return (K) map.get(key);
    }

    @Override
    public boolean delete(String key) {
        return map.remove(key)==null;
    }
}
